#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
MyGarden, by Limewood Media
Created on 21 jun 2011

@author: Joakim Lindskog

Copyright (c) 2011 Joakim Lindskog

This file is part of MyGarden.

    MyGarden is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MyGarden is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MyGarden.  If not, see <http://www.gnu.org/licenses/>.
'''
import os, gettext, sys, glob, locale
# Initialise translation
if len(sys.argv) > 1 and sys.argv[1] == "debug":
    # Testing
    localedir = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "locale")
else:
    # Deployed
    localedir = os.path.join("/usr","share","locale")
    localedir = localedir if os.path.exists(localedir) else os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "locale")

# Get the default locale on this system
locales = []
lc, encoding = locale.getdefaultlocale()
if (lc):
    locales = [lc]
language = os.environ.get('LANGUAGE', None)
if (language):
    locales += language.split(":")
arr = glob.glob(os.path.join(localedir, "*", "*", "mygarden.mo"))
for l in arr:
    # Get the available locales in the package
    l = l.replace(localedir, '').split(os.path.sep)[1]
    locales.append(l)

t = gettext.translation("mygarden", localedir, languages=locales, fallback=True, codeset="utf-8")
t.install(unicode=1)

from cocos.director import director;
import pyglet, menu
from util import config
from plants import plant

def main():
    '''
    Starts the game
    '''
    # Set up base resource paths
    pyglet.resource.path = ['../data/images', '../data/images/icons',\
                            '../data/anim', '../data/fonts',\
                            '../data/images/weather', '../data/sounds'];
    pyglet.resource.reindex();
    
    # Load plants from external plant definitions (in plants folder)
    search_folder = 'plants'
    plants_dir = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), search_folder)
    for file in os.listdir(plants_dir):
        plant_folder = os.path.join(plants_dir, file)
        if os.path.isdir(plant_folder):
            # This is a plant folder
            for f in os.listdir(plant_folder):
                name, ext = os.path.splitext(f)
                if ext == ".plant" and name == file:
                    # This is the definition file
                    def_path = os.path.join(plant_folder, f)
                    def_file = open(def_path, "r")
                    # Class variables
                    vars = {"id":name}
                    # Read each line in the file, but only catch valid ones
                    for line in def_file.readlines():
                        line = line.strip()
                        if line and line[0] != "#":
                            var = line.split("=")
                            if (var[0] != "name" and var[0] in config.PLANT_CLASS_VARIABLES):
                                vars[var[0]] = config.PLANT_CLASS_VARIABLES[var[0]](var[1])
                            elif var[0] == "name":
                                if name in plant.plant_names:
                                    plant.plant_names[name].append(var[1])
                                else:
                                    plant.plant_names[name] = [var[1]]
                    # Find localised name
                    name_found = False
                    for n in plant.plant_names[name]:
                        arr = n.split(":")
                        if t.info()['language'] == arr[0]:
                            vars["name"] = arr[1]
                            name_found = True
                            break
                    if not name_found:
                        for n in plant.plant_names[name]:
                            arr = n.split(":")
                            if t.info()['language'] == arr[0].split("_")[0]:
                                vars["name"] = arr[1]
                                name_found = True
                                break
                    if not name_found:
                        vars["name"] = plant.plant_names[name][0].split(":")[1]
                    # Add folder location
                    vars["folder"] = plant_folder
                    # Create plant class
                    cls = type(name.capitalize(), (plant.Plant,), vars)
                    # Initiate the class (load images)
                    loader = pyglet.resource.Loader([plant_folder])
                    cls.init(loader)
                    # Append the class to the list of plants
                    plant.list.append(cls)
                    break
    
    # Initiate director
    director.init(caption="My Garden",
                  width=config.SCREEN_WIDTH,
                  height=config.SCREEN_HEIGHT,
                  audio_backend='sdl');
    # Set icons
    icon_dir = '../data/images/icons'
    icon16 = os.path.join(icon_dir, 'icon16x16.png')
    icon32 = os.path.join(icon_dir, 'icon32x32.png')
    director.interpreter_locals["director"].window.set_icon(pyglet.image.load(icon16),\
                                                            pyglet.image.load(icon32))
    # Run
    director.run(menu.MainMenu().scene);

if(__name__ == "__main__"):
    main();